package be.groept.ace.enquete.model.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import be.groept.ace.enquete.model.beans.Question;
import be.groept.ace.enquete.model.beans.Survey;
import be.groept.ace.enquete.model.exceptions.DAOException;

public class QuestionDAOJDBCImpl implements QuestionDAO {

private Connection connection;
	
	public QuestionDAOJDBCImpl(Connection connection) {
		this.connection = connection;
	}
	
	@Override
	public void insertQuestionsOfSurvey(Survey survey) throws DAOException {
		
		PreparedStatement ps = null;
		try {
			String sql = "INSERT INTO question (text, surveyID, freeText, possibleAnswer) VALUES (?, ?, ?, ?)";
			ps = connection.prepareStatement( sql, Statement.RETURN_GENERATED_KEYS);
			for (Question question : survey.getQuestionSet()) {
				ps.setString(1, question.getText());
				ps.setInt(2, survey.getId());
				ps.setBoolean(3, question.isFreeText());
				ps.setString(4, question.getPossibleAnswer());
				ps.addBatch();
			}
			ps.executeBatch(); 
		} catch (SQLException sqle) {
			throw new DAOException(sqle);
		} finally {
			
			if (ps != null) {
				try {
					ps.close();
				} catch (SQLException sqle) {
					//log error
				}
			}
		}
	}
	
	public Question map(ResultSet resultSet, Survey survey) throws SQLException {
		Question question = new Question();
		question.setId(resultSet.getInt("question.id"));
		question.setText(resultSet.getString("question.text"));
		question.setPossibleAnswer(resultSet.getString("question.possibleAnswer"));
		question.setFreeText(resultSet.getBoolean("question.freeText"));
		question.setSurvey(survey);
		return question;
	}
	
}
